from django.db import models

# Create your models here.
from django.db import models
from django.contrib.auth.models import User


class PetType(models.Model):
    """宠物类型（如猫、狗、其他）"""
    name = models.CharField(max_length=50, verbose_name="类型名称")

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "宠物类型"
        verbose_name_plural = "宠物类型"


class Pet(models.Model):
    """宠物信息"""
    STATUS_CHOICES = [
        ('available', '可领养'),
        ('adopted', '已领养'),
        ('pending', '审核中'),
    ]

    name = models.CharField(max_length=100, verbose_name="名字")
    type = models.ForeignKey(PetType, on_delete=models.SET_NULL, null=True, verbose_name="类型")
    age = models.PositiveIntegerField(verbose_name="年龄（岁）")
    gender = models.CharField(max_length=10, choices=[('male', '公'), ('female', '母')], verbose_name="性别")
    description = models.TextField(verbose_name="描述")
    image = models.ImageField(upload_to='pets/', verbose_name="照片")
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='available', verbose_name="状态")
    created_time = models.DateTimeField(auto_now_add=True, verbose_name="发布时间")

    def __str__(self):
        # 修复：直接访问外键对象的name属性，并处理可能为None的情况
        type_name = self.type.name if self.type else '未知类型'
        return f"{self.name}（{type_name}）"

    class Meta:
        verbose_name = "宠物"
        verbose_name_plural = "宠物"


class AdoptionApplication(models.Model):
    """领养申请"""
    STATUS_CHOICES = [
        ('pending', '待审核'),
        ('approved', '已通过'),
        ('rejected', '未通过'),
    ]

    pet = models.ForeignKey(Pet, on_delete=models.CASCADE, verbose_name="申请领养的宠物")
    applicant = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="申请人")
    phone = models.CharField(max_length=20, verbose_name="联系电话")
    address = models.CharField(max_length=200, verbose_name="居住地址")
    reason = models.TextField(verbose_name="领养理由")
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending', verbose_name="状态")
    created_time = models.DateTimeField(auto_now_add=True, verbose_name="申请时间")
    reply = models.TextField(blank=True, null=True, verbose_name="审核回复")

    def __str__(self):
        return f"{self.applicant.username} 申请领养 {self.pet.name}"

    class Meta:
        verbose_name = "领养申请"
        verbose_name_plural = "领养申请"